/*
 * @(#)WorldViewerScreen.java     14/08/02
 * 
 * Author             Rick Wilson
 * Copyright (c) 2014 Rick Wilson
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of 'Taareekah' nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */



package gui;

//~--- non-JDK imports --------------------------------------------------------

import com.jme3.asset.AssetManager;
import com.jme3.input.InputManager;
import com.jme3.material.Material;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Quad;

import core.GameScriptManager;
import core.Main;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.NiftyEventSubscriber;
import de.lessvoid.nifty.controls.ButtonClickedEvent;
import de.lessvoid.nifty.controls.Console;
import de.lessvoid.nifty.controls.ConsoleCommands;
import de.lessvoid.nifty.controls.RadioButton;
import de.lessvoid.nifty.controls.RadioButtonStateChangedEvent;
import de.lessvoid.nifty.controls.TextField;
import de.lessvoid.nifty.elements.Element;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;

import groovy.lang.Binding;

import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import world.Terrain;
import world.World;

//~--- JDK imports ------------------------------------------------------------

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author rick
 */
public class WorldViewerScreen implements ScreenController {

    /** Field description */
    private Nifty	nifty;

    /** Field description */
    private Screen	screen;

    /** Field description */
    private ViewPort	view_port;

    /** Field description */
    private Node	root_node;

    /** Field description */
    private Node	gui_node;

    /** Field description */
    private AssetManager	asset_manager;

    /** Field description */
    private TextField	temperature_textfield;

    /** Field description */
    private TextField	drainage_textfield;

    /** Field description */
    private TextField	rainfall_textfield;

    /** Field description */
    private TextField	elevation_textfield;

    /** Field description */
    private TextField	biome_textfield;

    /** Field description */
    private TextField	position_textfield;

    /** Field description */
    private TextField	save_filename_textfield;

    /** Field description */
    private RadioButton	temperature_radio_button;

    /** Field description */
    private RadioButton	drainage_radio_button;

    /** Field description */
    private RadioButton	rainfall_radio_button;

    /** Field description */
    private RadioButton	elevation_radio_button;

    /** Field description */
    private RadioButton	biome_radio_button;

    /** Field description */
    private World	world;

    /** Field description */
    private Main	app;

    /** Field description */
    private Geometry	grid;

    /** Field description */
    private Material	elevation_material;

    /** Field description */
    private Material	temperature_material;

    /** Field description */
    private Material	rainfall_material;

    /** Field description */
    private Material	volcanism_material;

    /** Field description */
    private Material	drainage_material;

    /** Field description */
    private Material	biome_material;

    /** Field description */
    private boolean	is_initialized;

    /** Field description */
    private InputManager	input_manager;

    /** Field description */
    private Console	console;

    /**
     *
     * @param app
     */
    public WorldViewerScreen(Main app) {
	this.root_node		= app.getRootNode();
	this.view_port		= app.getViewPort();
	this.gui_node		= app.getGuiNode();
	this.asset_manager	= app.getAssetManager();
	this.app		= app;
	this.input_manager	= app.getInputManager();
    }

    /**
     * Method description
     *
     */
    private void reset() {
	elevation_material	= null;
	temperature_material	= null;
	rainfall_material	= null;
	volcanism_material	= null;
	drainage_material	= null;
	biome_material		= null;
	gui_node.detachChild(grid);
	grid		= null;
	world		= null;
	is_initialized	= false;
    }

    /**
     * Method description
     *
     *
     * @throws Exception
     */
    private void createGridAndMaterials() throws Exception {
	if (is_initialized) {
	    return;
	}

	Element	layer			= screen.findElementByName("world_viewer_layer0");
	Element	panel			= screen.findElementByName("world_viewer_control_panel");
	Element	console_panel		= screen.findElementByName("console_control");
	float	screen_height		= (float) layer.getHeight();
	float	screen_width		= (float) layer.getWidth();
	float	panel_height		= (float) console_panel.getHeight();
	float	panel_width		= (float) panel.getWidth();
	float	available_width		= screen_width - panel_width;
	float	available_height	= screen_height - panel_height;
	float	size			= available_width;

	if (available_height < available_width) {
	    size	= available_height;
	}

	world	= Main.getWorld();

	Terrain	terrain	= world.getTerrain();

	grid	= new Geometry("grid", new Quad(size, size));
	grid.setLocalTranslation(panel_width, panel_height, -1.0f);
	elevation_material	= terrain.getTerrainMap("elevation").createMaterial(asset_manager);
	temperature_material	= terrain.getTerrainMap("temperature").createMaterial(asset_manager);
	rainfall_material	= terrain.getTerrainMap("rainfall").createMaterial(asset_manager);
	drainage_material	= terrain.getTerrainMap("drainage").createMaterial(asset_manager);
	biome_material		= terrain.getBiomeMap().createMaterial(asset_manager);
	volcanism_material	= terrain.getTerrainMap("volcanism").createMaterial(asset_manager);
	grid.setMaterial(biome_material);
	gui_node.attachChild(grid);
	is_initialized	= true;
    }

    /**
     *
     * @param nifty
     * @param screen
     */
    @Override
    public void bind(Nifty nifty, Screen screen) {
	this.nifty			= nifty;
	this.screen			= screen;
	temperature_textfield		= screen.findNiftyControl("world_viewer_temperature_textfield",
		TextField.class);
	drainage_textfield		= screen.findNiftyControl("world_viewer_drainage_textfield", TextField.class);
	rainfall_textfield		= screen.findNiftyControl("world_viewer_rainfall_textfield", TextField.class);
	biome_textfield			= screen.findNiftyControl("world_viewer_biome_textfield", TextField.class);
	position_textfield		= screen.findNiftyControl("world_viewer_position_textfield", TextField.class);
	elevation_textfield		= screen.findNiftyControl("world_viewer_elevation_textfield", TextField.class);
	save_filename_textfield		= screen.findNiftyControl("world_viewer_save_filename_textfield",
		TextField.class);
	temperature_radio_button	= screen.findNiftyControl("world_viewer_temperature_radio_button",
		RadioButton.class);
	drainage_radio_button		= screen.findNiftyControl("world_viewer_drainage_radio_button",
		RadioButton.class);
	rainfall_radio_button		= screen.findNiftyControl("world_viewer_rainfall_radio_button",
		RadioButton.class);
	biome_radio_button		= screen.findNiftyControl("world_viewer_biome_radio_button", RadioButton.class);
	elevation_radio_button		= screen.findNiftyControl("world_viewer_elevation_radio_button",
		RadioButton.class);
	temperature_textfield.setText("0");
	drainage_textfield.setText("0");
	rainfall_textfield.setText("0");
	biome_textfield.setText("None");
	position_textfield.setText("(0, 0)");
	elevation_textfield.setText("0");
	save_filename_textfield.setText("");
	console	= screen.findNiftyControl("console_control", Console.class);

	ConsoleCommands		console_commands	= new ConsoleCommands(nifty, console);
	ExecuteScriptCommand	script_command		= new ExecuteScriptCommand(console);

	console_commands.registerCommand("execute", script_command);
	console_commands.enableCommandCompletion(true);
	screen.findElementByName("console_control#textInput").setFocus();
    }

    /**
     *
     */
    @Override
    public void onStartScreen() {
	try {
	    createGridAndMaterials();
	} catch (Exception ex) {
	    Logger.getLogger(WorldViewerScreen.class.getName()).log(Level.SEVERE, "Couldnt create grid and materials",
			     ex);
	}
    }

    /**
     *
     */
    @Override
    public void onEndScreen() {
	reset();
    }

    /**
     *
     * @param id
     * @param event
     * @throws Exception
     */
    @NiftyEventSubscriber(id = "world_viewer_back_from_viewer_button")
    public void backFromViewerScreenButtonHandler(String id, ButtonClickedEvent event) throws Exception {
	this.nifty.gotoScreen("start");
    }

    /**
     *
     * @param id
     * @param event
     * @throws Exception
     */
    @NiftyEventSubscriber(id = "world_viewer_save_world_button")
    public void saveWorldButtonHandler(String id, ButtonClickedEvent event) throws Exception {
	String	save_filename	= save_filename_textfield.getDisplayedText();

	if (save_filename == "") {
	    world.save();
	} else {
	    world.save(save_filename);
	}
    }

    /**
     *
     * @param id
     * @param event
     */
    @NiftyEventSubscriber(id = "world_viewer_elevation_radio_button")
    public void elevationRadioButtonPressed(String id, RadioButtonStateChangedEvent event) {
	grid.setMaterial(elevation_material);
    }

    /**
     *
     * @param id
     * @param event
     */
    @NiftyEventSubscriber(id = "world_viewer_temperature_radio_button")
    public void temperatureRadioButtonPressed(String id, RadioButtonStateChangedEvent event) {
	grid.setMaterial(temperature_material);
    }

    /**
     *
     * @param id
     * @param event
     */
    @NiftyEventSubscriber(id = "world_viewer_rainfall_radio_button")
    public void rainfallRadioButtonPressed(String id, RadioButtonStateChangedEvent event) {
	grid.setMaterial(rainfall_material);
    }

    /**
     *
     * @param id
     * @param event
     */
    @NiftyEventSubscriber(id = "world_viewer_drainage_radio_button")
    public void drainageRadioButtonPressed(String id, RadioButtonStateChangedEvent event) {
	grid.setMaterial(drainage_material);
    }

    /**
     *
     * @param id
     * @param event
     */
    @NiftyEventSubscriber(id = "world_viewer_biome_radio_button")
    public void biomeRadioButtonPressed(String id, RadioButtonStateChangedEvent event) {
	grid.setMaterial(biome_material);
    }

    /**
     *
     * @param id
     * @param event
     */
    @NiftyEventSubscriber(id = "world_viewer_volcanism_radio_button")
    public void volcanismRadioButtonPressed(String id, RadioButtonStateChangedEvent event) {
	grid.setMaterial(volcanism_material);
    }

    /**
     * Class description
     *
     *
     * @author         Enter your name here...
     */
    private static class ExecuteScriptCommand implements ConsoleCommands.ConsoleCommand {

	/** Field description */
	private Console	console;

	/**
	 * Constructs ...
	 *
	 *
	 * @param console
	 */
	public ExecuteScriptCommand(Console console) {
	    this.console	= console;
	}

	/**
	 * Method description
	 *
	 *
	 * @param strings
	 */
	@Override
	public void execute(String[] strings) {
	    if (strings.length < 2) {
		return;
	    }

	    String		filename	= strings[1];
	    GameScriptManager	gsm		= Main.getScriptManager();
	    GroovyScriptEngine	gse		= gsm.getGroovyEngine();
	    Binding		binding		= gsm.createBinding();

	    binding.setVariable("world", Main.getWorld());

	    try {
		gsm.runScriptWithBinding(filename, binding);
	    } catch (ResourceException ex) {
		console.output("Invalid file: " + filename);
		console.output(ex.getLocalizedMessage());
		Logger.getLogger(ExecuteScriptCommand.class.getName()).log(Level.SEVERE, null, ex);
	    } catch (ScriptException ex) {
		console.output("Could not parse: " + filename);
		console.output(ex.getLocalizedMessage());
		Logger.getLogger(WorldViewerScreen.class.getName()).log(Level.SEVERE, null, ex);
	    } catch (Exception ex) {
		console.output("Exception: " + filename);
		console.output(ex.getLocalizedMessage());
		Logger.getLogger(WorldViewerScreen.class.getName()).log(Level.SEVERE, null, ex);
	    }
	}
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
